package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.constant.SocketMessageEnum;
import com.example.domain.ChatFriendRel;
import com.example.domain.ChatMessage;
import com.example.domain.ChatUser;
import com.example.mapper.ChatFriendRelMapper;
import com.example.mapper.ChatMessageMapper;
import com.example.mapper.ChatUserMapper;
import com.example.service.IWebSocketServer;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * WebSocket支撑类，需要继承此类
 *
 * @Author: 不是菜鸡爱编程
 * @Date: 2024/01/01/9:28
 * @Description:
 */
@Service
public class WebSocketServerSupport implements IWebSocketServer {
    private static ChatMessageMapper chatMessageMapper;
    private static ChatUserMapper chatUserMapper;
    private static ChatFriendRelMapper chatFriendRelMapper;

    @Autowired
    private void setChatMessageMapper(ChatMessageMapper chatMessageMapper) {
        WebSocketServerSupport.chatMessageMapper = chatMessageMapper;
    }

    @Autowired
    private void setChatUserMapper(ChatUserMapper chatUserMapper) {
        WebSocketServerSupport.chatUserMapper = chatUserMapper;
    }

    @Autowired
    private void setChatFriendRelMapper(ChatFriendRelMapper chatFriendRelMapper) {
        WebSocketServerSupport.chatFriendRelMapper = chatFriendRelMapper;
    }

    /**
     * 日志
     */
    private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerSupport.class);
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServerSupport> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId;


    /**
     * 连接建立成功调用的方法
     * 1.在连接之后查询一下未读消息
     */
    @OnOpen
    @Override
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        // 更改用户登陆状态
        LambdaUpdateWrapper<ChatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ChatUser::getIsOnline, 0)
                .eq(ChatUser::getId, userId);
        // 将用户更新为在线
        chatUserMapper.update(updateWrapper);
        LOG.info("用户id连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        // 在线的用户id集合
        List<String> nowUserIdList = getUserIdList();
        // 新登陆的用户id为userId，现在需要通知他的好友“他已上线”
        MPJLambdaWrapper<ChatUser> wrapper = new MPJLambdaWrapper<>();
        //查询user表id字段
        wrapper.select(ChatUser::getId)
                .leftJoin(ChatFriendRel.class, ChatFriendRel::getFriendId, ChatUser::getId)
                .eq(ChatFriendRel::getUserId, userId)
                .eq(ChatFriendRel::getStatus, 0);
        // 需要通知的全部好友
        List<Integer> allFriendIdList = chatUserMapper.selectJoinList(Integer.class, wrapper)
                // 筛选出在线的好友
                .stream().filter(user -> nowUserIdList.contains(user.toString()))
                .collect(Collectors.toList());
        for (Integer friendId : allFriendIdList) {
            System.out.println("需要通知的全部好友：" + friendId);
        }
        ChatUser chatUser = chatUserMapper.selectOne(new LambdaQueryWrapper<ChatUser>()
                .eq(ChatUser::getId, userId));
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", SocketMessageEnum.USER_LOGIN.getStatus());
            jsonObject.put("code", 200);
            jsonObject.put("data", userId);
            jsonObject.put("msg", "您的好友" + chatUser.getNickName() + "上线");
            sendInfo(jsonObject.toJSONString(), allFriendIdList);
        } catch (IOException e) {
            LOG.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    @Override
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        LOG.info("用户id退出:" + userId + ",当前在线人数为:" + getOnlineCount());
        // 更改用户登陆状态
        LambdaUpdateWrapper<ChatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ChatUser::getIsOnline, 1)
                .eq(ChatUser::getId, userId);
        // 将用户更新为在线
        chatUserMapper.update(updateWrapper);
        // 用户离线，将状态推送给其他好友
        // 在线的用户id集合
        List<String> nowUserIdList = getUserIdList();
        // 新登陆的用户id为userId，现在需要通知他的好友“他已离线”
        MPJLambdaWrapper<ChatUser> wrapper = new MPJLambdaWrapper<>();
        //查询user表id字段
        wrapper.select(ChatUser::getId)
                .leftJoin(ChatFriendRel.class, ChatFriendRel::getFriendId, ChatUser::getId)
                .eq(ChatFriendRel::getUserId, userId)
                .eq(ChatFriendRel::getStatus, 0);
        // 需要通知的全部好友
        List<Integer> allFriendIdList = chatUserMapper.selectJoinList(Integer.class, wrapper)
                // 筛选出在线的好友
                .stream().filter(user -> nowUserIdList.contains(user.toString()))
                .collect(Collectors.toList());
        for (Integer friendId : allFriendIdList) {
            System.out.println("需要通知的全部好友：" + friendId);
        }
        ChatUser chatUser = chatUserMapper.selectOne(new LambdaQueryWrapper<ChatUser>()
                .eq(ChatUser::getId, userId));
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", SocketMessageEnum.USER_LOGOUT.getStatus());
            jsonObject.put("code", 200);
            jsonObject.put("data", userId);
            jsonObject.put("msg", "您的好友" + chatUser.getNickName() + "离线");
            sendInfo(jsonObject.toJSONString(), allFriendIdList);
        } catch (IOException e) {
            LOG.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    @Override
    public void onMessage(String message, Session session) {
        LOG.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StrUtil.isNotBlank(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUser", Integer.valueOf(this.userId));
                Date nowDate = new Date();
                jsonObject.put("createTime", nowDate);
                LOG.info("jsonObject:{}", jsonObject);
                String toUserId = jsonObject.getString("toUser");
                String content = jsonObject.getString("message");
                //传送给对应toUserId用户的websocket
                LOG.info("webSocketMap:{}", webSocketMap);
                if (StrUtil.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                } else {
                    LOG.error("请求的userId:" + toUserId + "不在该服务器上");
                    //否则不在这个服务器上，发送到mysql或者redis
                }
                ChatMessage chatMessage = new ChatMessage(null, content, this.userId, toUserId, nowDate, 1);
                LOG.info("持久化消息:{}", chatMessage);
                // 将信息持久化到数据库
                chatMessageMapper.insert(chatMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户异常调用
     *
     * @param session
     * @param error
     */
    @OnError
    @Override
    public void onError(Session session, Throwable error) {
        LOG.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     */
    public void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        LOG.info("发送消息到:" + userId + "，报文:" + message);
        if (StrUtil.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            LOG.error("用户" + userId + ",不在线！");
            // 将消息存入数据库、设为未读
        }
    }

    /**
     * 用户是否在线状态变化，推送给其好友
     *
     * @param message
     * @param userIdList
     * @throws IOException
     */
    public void sendInfo(String message, @PathParam("userIdList") List<Integer> userIdList) throws IOException {
        for (Integer friendId : userIdList) {
            if (StrUtil.isNotBlank(friendId.toString()) && webSocketMap.containsKey(friendId.toString())) {
                webSocketMap.get(friendId.toString()).sendMessage(message);
            } else {
                LOG.error("用户" + friendId + ",不在线！");
                // 将消息存入数据库、设为未读
            }
        }
    }

    /**
     * 获取用户id列表
     *
     * @return {@link List}<{@link String}>
     */
    private List<String> getUserIdList() {
        return new ArrayList<>(webSocketMap.keySet());
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServerSupport.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServerSupport.onlineCount--;
    }
}